package values.inventory
{
import values.item.IItemValue;
import values.item.INumbericItemValue;
import values.item.ItemValue;

/**
 * NumbericItemInventoryValue
 * @author jliang
 *
 */
public class NumbericItemInventoryValue extends InventoryValue
{
	//==========================================================================
	//  Constructor
	//==========================================================================
	public function NumbericItemInventoryValue()
	{
		super();
	}
	//==========================================================================
	//  Overridden methods: InventoryValue
	//==========================================================================
	override public function addItem(value:IItemValue):*
	{				
		var target:INumbericItemValue = value as INumbericItemValue;
		
		if (isFull)
		{
			dispatchAddItemFailEvent(target);
			
			return null;
		}
		
		var resultVO:INumbericItemValue;
		
		var matchItem:INumbericItemValue = findItem(value.key);
		
		if (matchItem)
		{
			matchItem.concat(INumbericItemValue(value));
			resultVO = matchItem;
		}
		else
		{
			resultVO = INumbericItemValue(value).clone();
			items.push(resultVO);
		}
		
		if (isFull)
		{
			dispatchFullEvent();
		}
		return resultVO;
	}
	
	override public function removeItem(value:IItemValue):*
	{
		var target:INumbericItemValue = value as INumbericItemValue;
		var matchItem:INumbericItemValue = findItem(value.key);
		
		var copy:INumbericItemValue = target.clone();
		var temp:Number = -copy.num;
		copy.num = temp;
		
		matchItem.concat(copy);
		
		return null;
	}
	
	override public function hasEnoughSpace(value:IItemValue):Boolean
	{
		if (isFull) return false;
		
		if (findItem(value.key) != null)
		{
			return true;
		}
		else
		{
			if (items.length + 1 > currentSpace) return false;
		}
		
		return true;
	}
	
	override public function getItemNum(itemKey:String, ...args):Number
	{
		for each (var vo:INumbericItemValue in items)
		{
			if (vo.key == itemKey)
			{
				return vo.num;
			}
		}
		return 0;
	}
    
    override public function getItemNumByKey(itemKey:String):Number
    {
        var num:Number = 0;
        for each (var item:INumbericItemValue in items)
        {
            if (item.key == itemKey) num += item.num;
        }
        return num;
    }
	
	override protected function findItem(itemKey:String):*
	{
		for each (var vo:ItemValue in items)
		{
			if (vo.key == itemKey) return vo;
		}
		return null;
	}
	
	public function getItem(itemKey:String):INumbericItemValue
	{
		return findItem(itemKey);
	}
}
}





